package com.ky.server.dao;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.ky.common.entity.KyFile;
import com.ky.server.util.ConfigConstants;
import com.ky.server.util.PropertiesUtil;

public class FileDao {

	private static HashMap<Long, KyFile> fileMap=new HashMap<>();
	private static Document document;
	private static String xmlPath=PropertiesUtil.getProperty(ConfigConstants.SERVER_FILES_PATH_KEY);
	
	static {
		SAXReader saxReader = new SAXReader();
		try {
			document = saxReader.read(xmlPath);
			Element rootElement = document.getRootElement();
			List<Element> elements = rootElement.elements("file");
			for (Element element : elements) {
				long id = Long.parseLong( element.attributeValue("id").trim());
				String name = element.elementTextTrim("name");
				double size=Double.parseDouble(element.elementTextTrim("size"));
				String path = element.elementTextTrim("path");
				fileMap.put(id, new KyFile(id, name, size, path));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
	//查找并返回全部文件
	
	public static KyFile[] getFileList() {
		//将map中的值转为collection集合
		Collection<KyFile> files =fileMap.values();
		//将collection集合转为数组，方便后面循环遍历输出
		return files.toArray(new KyFile[] {});
	}
	
	//通过id查询并返回一个要下载的文件，并读取为字节数组
	public static byte[] getFileBsById(Long id) {
		KyFile kyFile = fileMap.get(id);
		String path = kyFile.getPath();
		File destFile = new File(path);
		if(!destFile.exists()) {
			return null;
		}
		byte[] bs=null;
		try {
			bs=FileUtils.readFileToByteArray(destFile);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bs;
	}
}
